<template>
	<div class="resource_box">
		<el-tabs v-model="activeName" @tab-add='openAddBig' @tab-remove='tabRemove' type="card" :closable='!isChange' :addable='!isChange' :editable='!isChange'>
			<el-tab-pane :label="item.title && item.seq?('（'+item.seq+'）'+item.title):'新增步骤'" :name="index + ''" :disabled='isChange' v-for='(item,index) in dataList'>
				<div class="add_input clearfix">
					<span class="search_label">步骤序号:</span>
					<el-input placeholder="请输入步骤序号" @input='hasChanged' v-model="item.seq" style="width:200px;margin-left: 10px" />
					<span class="search_label">步骤名称:</span>
					<el-input placeholder="请输入步骤名称" @input='hasChanged' v-model="item.title" style="width:200px;margin-left: 10px" maxlength='12' />
					<el-button type='primary' size='small' @click='openAdd()' class='fr'>添加小步骤</el-button>
				</div>
				<el-table :data="item.stepSmallList" border>
					<el-table-column prop="smallSeq" label="步骤编号" align='center'>
						<template slot-scope="scope">
							<el-input @input='hasChanged' v-model='scope.row.smallSeq' placeholder='请输入步骤编号' style='width: 160px;'></el-input>
						</template>
					</el-table-column>
					<el-table-column prop="smallTitle" label="步骤名" align='center'>
						<template slot-scope="scope">
							<el-input @input='hasChanged' v-model='scope.row.smallTitle' placeholder='请输入步骤名' style='width: 200px;'></el-input>
						</template>
					</el-table-column>
					<el-table-column prop="smallExpectScore" label="类型" align='center'>
						<template slot-scope="scope">
							<el-select @change='hasChanged' v-model="scope.row.smallType" placeholder="类型" style="width:200px">
								<el-option v-for="item in smallTypes" :key="item.value" :label="item.label" :value="item.value" placeholder='请选择步骤类型'>
								</el-option>
							</el-select>
						</template>
					</el-table-column>
					<el-table-column prop="smallExpectTime" label="标准用时" align='center'>
						<template slot-scope="scope">
							<el-input-number @change='hasChanged' v-model="scope.row.smallExpectTime" :min='1' :step="1" step-strictly label="请输入标准用时" size='small'></el-input-number>
						</template>
					</el-table-column>
					<el-table-column prop="smallExpectScore" label="分数" align='center'>
						<template slot-scope="scope">
							<el-input-number @change='hasChanged' :disabled='scope.row.smallType == 2' v-model="scope.row.smallExpectScore" :min='1' :step="1" step-strictly label="请输入分数" size='small'></el-input-number>
						</template>
					</el-table-column>
					<el-table-column prop="majorId" label="操作" width='360' align='center'>
						<template slot-scope="scope">
							<el-button type="danger" size='small' @click="openDelete(scope.row,scope.$index)">删除</el-button>
							<el-button type='primary' size='small' @click="openExp(scope.row,scope.$index)">分数说明</el-button>
							<el-button type='success' size='small' @click="openTopics(scope.row,scope.$index)" v-if='scope.row.smallType == 2'>试题管理</el-button>
						</template>
					</el-table-column>
				</el-table>
				<div class="add_btns add_btns1" v-if="isChange">
					<el-button type='primary' size='small' @click='checkAdd()'>保存</el-button>
				</div>
			</el-tab-pane>
		</el-tabs>
		<el-dialog title="分数说明" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' width='420px' destroy-on-close :visible.sync="addShow" class='paddingSmall coursedialog'>
			<el-form :model="addForm" :rules="rules" ref='addForm'>
				<el-form-item label="分数说明" :label-width="labelWidth" prop="smallScoringModel">
					<el-input v-model="addForm.smallScoringModel" resize='none' type="textarea" :rows="5" placeholder="请输入步骤说明" autocomplete="off">
					</el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeExp">取 消</el-button>
				<el-button type="primary" @click="addExp">保 存</el-button>
			</div>
		</el-dialog>
		<el-dialog title="试题管理" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' width='1450px' destroy-on-close :visible.sync="openSelect" class='paddingSmall coursedialog'>
			<el-button type="primary" style="margin:0 0 10px 10px" @click="allScore" plain :disabled='!topicIds || topicIds.length<=0'>批量赋分</el-button>
			<el-button type="danger" style="margin:0 0 10px 10px" @click="allDelete" plain :disabled='!topicIds || topicIds.length<=0'>批量删除</el-button>
			<el-button type="primary" style="margin:0 0 10px 10px" @click="reGet">添加试题</el-button>
			<el-table :data="smallTopicList" border @select-all='selectionAllTopChange' @select='selectionTopChange' row-key="vrTopicId" ref='selectList'>
				<el-table-column width="55" align="center" type="selection" :reserve-selection='true' />
				<el-table-column prop="question" label="题干" width="320">
					<template slot-scope="scope">
						<span @click="openInfo(scope.row)" class="editor_box pointer" v-html="scope.row.question"></span>
					</template>
				</el-table-column>
				<el-table-column prop="questionType" label="题型" align="center">
					<template slot-scope="scope">
						<span v-for='item in questionTypes' v-if="item.value == scope.row.questionType">{{item.name}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="difficulty" label="难度" align="center">
					<template slot-scope="scope">
						<span v-for='item in difficultys' v-if="item.value == scope.row.difficulty">{{item.name}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="score" label="分数" align="center">
					<template slot-scope="scope">
						<el-input-number @change='hasChanged' v-model="scope.row.score" :min='1' :step="1" step-strictly label="请输入分数" size='small'></el-input-number>
					</template>
				</el-table-column>
			</el-table>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetTopic">取 消</el-button>
				<el-button type="primary" @click="addTopic">保 存</el-button>
			</div>
			<el-dialog title="题库选择" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' width='1300px' destroy-on-close :visible.sync="openTopic" class='paddingSmall coursedialog'>
				<span class="search_label">题干:</span>
				<el-input v-model='question' placeholder="请输入题干" style="width:200px;margin-left: 10px" clearable></el-input>
				<span class="search_label">题型:</span>
				<el-select v-model='questionType' placeholder="请选择题型" @change='currentChange(1)' style="width:200px" clearable>
					<el-option v-for="item in questionTypes" :key="item.value" :label="item.name" :value="item.value">
					</el-option>
				</el-select>
				<span class="search_label">难度:</span>
				<el-select v-model='difficulty' placeholder="试题难度" @change='currentChange(1)' style="width:200px" clearable>
					<el-option v-for="item in difficultys" :key="item.value" :label="item.name" :value="item.value">
					</el-option>
				</el-select>
				<span class="search_label">所属专业:</span>
				<el-select v-model="majorId" placeholder="请选择所属专业" style="width:200px;margin-left: 10px" clearable>
					<el-option v-for="item in majors" :label="item.name" :value="item.id">
					</el-option>
				</el-select>
				<el-button type="primary" style="margin:0 0 10px 10px" @click="currentChange(1)">搜索</el-button>
				<el-table :data="tableDate" border @select-all='selectionAllChange' @select='selectionChange' row-key="vrTopicId" ref='topicList'>
					<el-table-column width="55" align="center" type="selection" :reserve-selection='true' />
					<el-table-column prop="question" label="题干" width="320">
						<template slot-scope="scope">
							<span @click="openInfo(scope.row)" class="editor_box pointer" v-html="scope.row.question"></span>
						</template>
					</el-table-column>
					<el-table-column prop="questionType" label="题型" align="center">
						<template slot-scope="scope">
							<span v-for='item in questionTypes' v-if="item.value == scope.row.questionType">{{item.name}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="difficulty" label="难度" align="center">
						<template slot-scope="scope">
							<span v-for='item in difficultys' v-if="item.value == scope.row.difficulty">{{item.name}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="majorName" label="所属专业" align="center">
					</el-table-column>
				</el-table>
				<div style="margin: 10px; text-align: center;">
					<el-pagination background @current-change="currentChange" :current-page="pageNum" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="total">
					</el-pagination>
				</div>
				<div slot="footer" class="dialog-footer">
					<el-button @click="resetSelect">关闭</el-button>
				</div>
			</el-dialog>
		</el-dialog>
		<el-dialog title="批量赋分" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' width='300px' destroy-on-close :visible.sync="scoreShow" class='paddingSmall coursedialog'>
			<el-form :model="scoreForm" :rules="rules" ref="scoreForm" :inline="true">
				<el-form-item label="分数" prop="score" label-width="110px">
					<el-input-number v-model="scoreForm.score" :min='1' :step="1" step-strictly label="请输入分数" size='small'></el-input-number>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetScore">取消</el-button>
				<el-button type='primary' @click="checkScore">确定</el-button>
			</div>
		</el-dialog>
		<el-drawer :visible.sync="topicShow" :with-header="false" :size='450'>
			<div class="topic_info">
				<div class="topic_info_title">试题详情</div>
				<div class="topic_info_body beautifulScroll" v-if='topicShow'>
					<questionview :readonly='true' :allshow='true' :showanswer='true' :form="openForm"></questionview>
				</div>
			</div>
		</el-drawer>
	</div>
</template>

<script>
	import questionview from "@/components/question/questionview.vue"
	import { majorList } from '@/api/major.js'
	import { topicList, saveTopic, updateTopic, removeTopic, selectTopicDetail, topicExport, importTopic, downloadTemplate } from "@/api/topic.js"
	import { detailStepSave, detailStepRemove, detailStepList, smallTopicList } from '@/api/vrResourceDetailStep.js'
	export default {
		components: {
			questionview,
		},
		props: {
			vrResourceDetailId: {
				required: true,
				default: ''
			},
		},
		data() {
			var checkNumber = (rule, value, callback) => {
				if(!value || value == 0) {
					return callback(new Error('请填写数字'));
				} else if(isNaN(Number(value))) {
					return callback(new Error('请填写数字'));
				} else if(!Number.isInteger(Number(value))) {
					return callback(new Error('请输入整数'));
				} else {
					return callback();
				}
			};
			return {
				activeName: 0,
				dataList: [],
				labelWidth: '100px',
				addShow: false,
				addForm: {
					smallScoringModel: '',
					index: -1,
				},
				rules: {
					smallScoringModel: [{
						required: true,
						message: '请输入分数说明'
					}],
					score: [{
						validator: checkNumber
					}, {
						required: true,
						message: '请输入试题分数'
					}],
				},
				isChange: false,
				smallTypes: [{
					value: 1,
					label: "操作"
				}, {
					value: 2,
					label: "理论"
				}],
				tableDate: [],
				question: '',
				questionType: "",
				difficulty: "",
				majorId: "",
				pageNum: 1,
				pageSize: 10,
				total: 0,
				openTopic: false,
				openSelect: false,
				majors: [],
				questionTypes: [{
					name: '单选题',
					value: 'SINGLE'
				}, {
					name: '多选题',
					value: 'MULTIPLE'
				}, {
					name: '判断题',
					value: 'JUDGE'
				}],
				difficultys: [{
					name: '简单',
					value: 'SIMPLE'
				}, {
					name: '中等',
					value: 'MEDIUM'
				}, {
					name: '困难',
					value: 'DIFFICULTY'
				}],
				smallTopicList: [],
				topicIds: [],
				selectIds: [],
				openTopicIndex: -1,
				scoreShow: false,
				scoreForm: {
					score: 0
				},

				topicShow: false,
				openForm: {},
			}
		},
		created() {
			this.getResources();
			this.getMajorList();
		},
		mounted() {

		},
		methods: {
			openInfo(topic) {
				this.openForm = Object.assign({}, topic);
				this.topicShow = true;
			},
			allDelete() {
				this.$confirm('确认删除这些试题吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					var topicIds = [];
					var smallTopicList = [];
					this.smallTopicList.map(item => {
						if(!this.topicIds.includes(item.vrTopicId)) {
							smallTopicList.push(item);
							topicIds.push(item.vrTopicId)
						}
					})
					this.smallTopicList = JSON.parse(JSON.stringify(smallTopicList));
					this.topicIds = topicIds;
					this.$refs.selectList.clearSelection();
				}).catch(() => {});
			},
			resetScore() {
				this.scoreForm.score = 0;
				this.$nextTick(() => {
					this.$refs.scoreForm.clearValidate();
					this.scoreShow = false;
				})
			},
			checkScore() {
				this.$refs.scoreForm.validate((valid) => {
					if(valid) {
						this.smallTopicList.map(item => {
							if(this.topicIds.includes(item.vrTopicId)) {
								item.score = this.scoreForm.score
							}
						})
						this.$refs.selectList.clearSelection();
						this.resetScore();
					}
				})
			},
			allScore() {
				this.scoreForm = {
					score: 0
				}
				this.scoreShow = true;
			},
			selectionAllTopChange(selection) {
				var topicIds = [];
				if(selection && selection.length > 0) {
					selection.map(topic => {
						topicIds.push(topic.vrTopicId)
					})
				}
				this.topicIds = topicIds;
			},
			selectionTopChange(selection) {
				var topicIds = [];
				if(selection && selection.length > 0) {
					selection.map(topic => {
						topicIds.push(topic.vrTopicId)
					})
				}
				this.topicIds = topicIds;
			},
			resetSelect() {
				this.tableDate = [];
				this.question = '';
				this.questionType = '';
				this.difficulty = '';
				this.majorId = '';
				this.pageNum = 1;
				this.pageSize = 10;
				this.total = 0;
				this.$refs.topicList.clearSelection();
				this.openTopic = false;
			},
			resetTopic() {
				this.smallTopicList = [];
				this.selectIds = [];
				this.openTopicIndex = -1;
				this.openTopic = false;
				this.openSelect = false;
				this.$refs.selectList.clearSelection();
			},
			addTopic() {
				var smallTopicList = this.smallTopicList;
				if(smallTopicList && smallTopicList.length) {
					var smallExpectScore = 0
					var flag = smallTopicList.filter(item => {
						smallExpectScore += (+item.score)
						return !item.score
					})
					if(flag && flag.length) {
						this.$message({
							type: 'error',
							message: '请输入试题分数！'
						})
						return
					}
					this.dataList[+this.activeName].stepSmallList[this.openTopicIndex].smallExpectScore = smallExpectScore;
				} else {
					this.dataList[+this.activeName].stepSmallList[this.openTopicIndex].smallExpectScore = 0;
				}
				this.dataList[+this.activeName].stepSmallList[this.openTopicIndex].smallTopicList = smallTopicList;
				this.resetTopic();
				this.hasChanged();
			},
			selectionAllChange(selection) {
				var selectIds = [];
				var smallTopicList = [];
				if(selection && selection.length > 0) {
					selection.map(topic => {
						var pushItem = JSON.parse(JSON.stringify(topic));
						topic.checked = false;
						smallTopicList.push(topic);
						selectIds.push(topic.vrTopicId)
					})
				}
				this.selectIds = selectIds;
				this.smallTopicList = smallTopicList;
			},
			selectionChange(selection, row) {
				var selectIds = [];
				var smallTopicList = [];
				if(selection && selection.length > 0) {
					selection.map(topic => {
						var pushItem = JSON.parse(JSON.stringify(topic));
						topic.checked = false;
						smallTopicList.push(topic);
						selectIds.push(topic.vrTopicId)
					})
				}
				this.selectIds = selectIds;
				this.smallTopicList = smallTopicList;
			},
			reGet() {
				var selectIds = [];
				this.smallTopicList.map(item => {
					selectIds.push(item.vrTopicId)
				})
				this.selectIds = selectIds;
				this.question = '';
				this.questionType = '';
				this.difficulty = '';
				this.majorId = '';
				this.openTopic = true;
				this.currentChange(1);
			},
			currentChange(pageNum) {
				this.pageNum = pageNum;
				this.getDataList();
			},
			getDataList() {
				topicList({
					difficulty: this.difficulty,
					question: this.question,
					questionType: this.questionType,
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					majorId: this.majorId,
				}).then(async res => {
					this.tableDate = JSON.parse(JSON.stringify(res.data.list || []));
					this.total = res.data.total;
					this.tableDate.map(item => {
						if(this.selectIds.includes(item.vrTopicId)) {
							this.$nextTick(() => {
								this.$refs.topicList.toggleRowSelection(item, true);
							})
						}
					})
				})
			},
			getMajorList() {
				majorList({}).then(res => {
					this.majors = res.data || []
				})
			},
			hasChangeOver() {
				this.$emit('changeDoing', false);
				this.isChange = false;
			},
			hasChanged() {
				this.$emit('changeDoing', true);
				this.isChange = true;
			},
			openTopics(item, index) {
				this.smallTopicList = item.smallTopicList || [];
				this.openTopicIndex = index;
				this.openSelect = true;
			},
			tabRemove(name) {
				var data = this.dataList[+name];
				if(data.vrResourceDetailStepId) {
					detailStepRemove({
						vrResourceDetailStepId: data.vrResourceDetailStepId
					}).then(res => {
						this.dataList.splice(+name, 1)
					})
				} else {
					this.dataList.splice(+name, 1)
				}
			},
			openAddBig() {
				this.dataList.push({
					vrResourceDetailId: this.vrResourceDetailId,
					seq: '',
					title: '',
					stepSmallList: [],
				})
				this.activeName = (this.dataList.length - 1) + '';
			},
			checkAdd() {
				var data = this.dataList[+this.activeName]
				if(!data.seq) {
					this.$message({
						type: 'error',
						message: '请输入步骤序号！'
					})
					return
				}
				if(!data.title) {
					this.$message({
						type: 'error',
						message: '请输入步骤名称！'
					})
					return
				}
				var dataCodes = [];
				var codeCheck = false;
				var topicCheck = false;
				var flagArr = data.stepSmallList.filter(item => {
					if(item.smallSeq) {
						if(dataCodes.includes(item.smallSeq)) {
							codeCheck = true;
						} else {
							dataCodes.push(item.smallSeq)
						}
					}
					if(item.smallType == 2 && (!item.smallTopicList || item.smallTopicList.length <= 0)) {
						topicCheck = true
					}
					return !item.smallSeq || !item.smallTitle || !item.smallExpectTime || !item.smallExpectScore || !item.smallType
				})
				if(flagArr && flagArr.length) {
					this.$message({
						type: 'error',
						message: '步骤内容不完整！'
					})
					return
				}
				if(codeCheck) {
					this.$message({
						type: 'error',
						message: '资源编号不能重复！'
					})
					return
				}
				if(topicCheck) {
					this.$message({
						type: 'error',
						message: '理论步骤必选选择试题！'
					})
					return
				}
				data.vrResourceDetailId = this.vrResourceDetailId;
				detailStepSave(data).then(res => {
					if(res.code == '200') {
						this.$message({
							type: 'success',
							message: res.message
						})
						this.hasChangeOver();
					} else {
						this.$message({
							type: 'error',
							message: res.message
						})
					}
				})
			},
			openDelete(item, index) {
				this.dataList[+this.activeName].stepSmallList.splice(index, 1)
				this.hasChanged();
			},
			openAdd() {
				this.dataList[+this.activeName].stepSmallList.unshift({
					smallSeq: '',
					smallTitle: '',
					smallExpectTime: 1,
					smallExpectScore: 1,
					smallScoringModel: '',
					smallType: '',
					smallTopicList: [],
				})
				this.hasChanged();
			},
			openExp(item, index) {
				this.addForm.smallScoringModel = item.smallScoringModel || '';
				this.addForm.index = index;
				this.addShow = true;
			},
			addExp() {
				var addInfo = Object.assign({}, this.dataList[+this.activeName].stepSmallList[this.addForm.index], {
					smallScoringModel: this.addForm.smallScoringModel
				})
				this.$set(this.dataList[+this.activeName].stepSmallList, this.addForm.index, addInfo)
				this.closeExp();
				this.hasChanged();
			},
			closeExp() {
				this.addForm = {
					smallScoringModel: '',
					index: -1,
				}
				this.$nextTick(() => {
					this.$refs.addForm.clearValidate();
					this.addShow = false;
				})
			},
			getResources() {
				detailStepList({
					vrResourceDetailId: this.vrResourceDetailId
				}).then(res => {
					this.dataList = res.data || [];
					if(!this.dataList || this.dataList.length == 0) {
						this.openAddBig()
					}
				})
			},
		}
	}
</script>
<style type="text/css" scoped="scoped">
	.resource_box {
		width: 100%;
		box-sizing: border-box;
		padding: 0 20px;
	}
	
	.add_btns {
		height: auto;
		padding: 0 0 10px 0;
		text-align: right;
	}
	
	.add_btns1 {
		padding: 15px 0 0 0;
	}
	
	.add_input {
		height: auto;
		padding: 0 0 10px 0;
	}
</style>